package top.tagao.service_sms.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.tagao.service_sms.service.SmsService;
import top.tagao.service_sms.utils.RandomUtil;
import top.tagao.yygh.common.result.Result;
import top.tagao.yygh.vo.msm.MsmVo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/9 14:24
 */
@Api(tags = "短信服务")
@RestController
@RequestMapping("/api/sms")
public class SmsApiController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String>  redisTemplate;


    @ApiOperation(value = "发送手机验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //1. 判断Redis是否缓存有验证码 - { 不再发送  : 发送 }
        String code  = redisTemplate.opsForValue().get(phone);

        //2. Redis缓存有验证码不发送
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }

        //3. Redis缓存不存在验证码
        //4. 生成验证码
        code = RandomUtil.getSixBitRandom();
        //5. 调用service发送验证码
        MsmVo msmVo = new MsmVo();
        msmVo.setTemplateCode("SMS_235829276");
        msmVo.setPhone(phone);
        String finalCode = code;
        Map paramsMap = new HashMap< String,String>(){{
            put("code", finalCode);
        }};
        msmVo.setParam(paramsMap);

        boolean flag = smsService.send(msmVo);

        //6. 生成验证码存放到Redis,设置缓存时间
        if (flag) {
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("短信发送失败");
        }
    }
}
